﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace SmartCardClient.ViewModels
{
	public class DialogViewModel : ViewModel
	{
		#region fields

		private RelayCommand<object> _closeCommand;

		#endregion

		#region properties

		public RelayCommand<object> CloseCommand
		{
			get;
			private set;
		}

		#endregion

		#region events

		public event Action RequestClose;

		#endregion

		#region construction

		public DialogViewModel(Action closeAction)
		{
			if (closeAction == null)
			{throw new ArgumentNullException("closeAction");}

			RequestClose = closeAction;
			_closeCommand = new RelayCommand<object>(OnRequestClose);
		}

		#endregion

		protected virtual void OnRequestClose(object param)
		{
			SendRequestCloseEvent();
		}

		protected void SendRequestCloseEvent()
		{
			if (RequestClose != null)
			{
				if (Application.Current != null &&
					Application.Current.Dispatcher != Dispatcher.FromThread(Thread.CurrentThread))
				{ Application.Current.Dispatcher.BeginInvoke(new Action(SendRequestCloseEvent)); }
				else
				{
					RequestClose();
				}
			}
		}
	}
}
